require('babel-core/register');
require('babel-polyfill');
import React, { Component } from 'react'
import { render } from 'react-dom'
import { createStore } from 'redux';
import { BrowserRouter} from 'react-router-dom';
import search_reducer, { initState } from './reducers/search_reducer'
import { Provider } from 'react-redux'
import Main from './components/main'
import { List, Map } from 'immutable'

let rootElement = document.getElementById('root');

//服务器渲染的html中的js脚本里注入了_PRELOADED_STATE_属性
let preloadedState = window.__PRELOADED_STATE__

// Allow the passed state to be garbage-collected
delete window.__PRELOADED_STATE__

//将state转成immutable的形式
if (preloadedState) {
    for(var key in preloadedState) {
        preloadedState[key] = reconstruct(preloadedState[key]);
    }
}
//递归的将一个Object转换成immutable
function reconstruct(state) {
    let result = null;
    if(state instanceof Array){             //如果是一个Array，则转换成List
        state = state.map((item)=>{
            return reconstruct(item)
        })
        return List(state);
    } else if (typeof state === 'object') { //如果是一个Object，则转换成Map
        for(var key in state) {
            state[key] = reconstruct(state[key]);
        }
        return Map(state);
    } else {                                //否则直接返回
        return state;
    }
}

function secure() {
    // const hostname = location.hostname.substring(7, 11);
    // if (hostname == 'terx' || location.hostname == 'localhost') {
    //     // Create Redux store with initial state
    //
    //
    //
    // }
    const store = createStore(search_reducer, preloadedState);
    render(
        <Provider store={store}>
            <BrowserRouter>
                <Main/>
            </BrowserRouter>
        </Provider>,
        rootElement
    )
}
secure();




